from django.shortcuts import render, reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import timezone

# User Auth
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from .models import UserProfile

import uuid

"""
class UserAuthView(View):
    #  CBV(Class Base View) : Extend basic view class: django.view.View

    @method_decorator(login_required)
    def sign_up(self, request):

        # Check User is register or not
        state = None

        if request.method == 'POST':
            # authenticate user info
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            repeat_password = request.POST.get('repeat_password', '')
            phone = request.POST.get('phone', '')
            email = request.POST.get('email', '')

            if UserInfo.objects.filter(username=username):
                # The user had already register ...
                state = 'user_exist'
            else:
                # create user
                new_user = UserInfo.objects.create_user(username=username,
                                                        password=password,
                                                        phone=phone,
                                                        email=email)
                new_user.save()

                # redirect url: create user success
                return redirect('/book/')

        # Redirect
        content = {
            'state': state,
            'user': None,
        }

        return render(request, 'sign_up.html', content)

"""


# FBV : Function Base View
def index(request, username='admin'):
    if not username:
        username = 'admin'
    return render(request, "login/index.html", context={'username': username})


def register(request):
    """ Account Register."""
    
    # 提示信息
    message = '用户注册的提示信息.'

    if request.method == 'POST':
        # Register Form
        user_id = uuid.uuid4()
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        repeat_password = request.POST.get('repeat_password', '')
        department = request.POST.get('department', 'Risk')
        phone = request.POST.get('phone', '')
        email = request.POST.get('email', '')
        create_time = timezone.now()

        if username and password:
            if password == repeat_password:
                try:
                    # 若当前用户 User 存在
                    query_user = UserProfile.objects.get(username=username)
                    message = '当前用户名称已被注册, 请重新注册.'
                except UserProfile.DoesNotExist:
                    # 若当前用户 User 不存在, 创建用户
                    user = UserProfile.objects.create_user(uuid=user_id, username=username, password=password,
                                                           department=department,  phone=phone, email=email,
                                                           create_time=create_time)
                    user.save()

                    context = {
                        'username': username,
                        'password': password,
                        'message': "欢迎登陆"
                    }
                    return HttpResponseRedirect(reverse('login:login'))
                finally:
                    pass
            else:
                message = '注册用户的设置密码与重复密码不一致.'
        else:
            message = '注册用户或密码不合命名规范.'
    else:
        username = request.GET.get('username', '')
        password = request.GET.get('password', '')
        repeat_password = request.GET.get('repeat_password', '')
        department = request.GET.get('department', '')
        phone = request.GET.get('phone', '')
        email = request.GET.get('email', '')
        # request method: GET
        message = '欢迎注册.'
    
    context = {
        'username': username,
        'password': password,
        'repeat_password': repeat_password,
        'department': department,
        'phone': phone,
        'email': email,
        'message': message
    }

    return render(request, 'login/register.html', context=context)


def login(request):
    """ Check User Form ."""
    
    message = '登陆页面提示信息'
    
    if request.method == 'POST':
        # User Input
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')

        # auth user
        user = auth.authenticate(username=username, password=password)

        # if user is not None and user.is_active:
        if user is not None:
            # auth success and account is active
            auth.login(request, user)
            # 跳转用户欢迎页面
            return HttpResponseRedirect(reverse('login:content', args=(username,)))
        else:
            # auth failed or account is not active
            message = '用户不存在 或 输入用户名、密码错误.'
    else:
        # message
        username = request.GET.get('username', '')
        password = request.GET.get('password', '')
        message = '欢迎登陆.'

    context = {
        'username': username,
        'password': password,
        'message': message
    }

    return render(request, 'login/login.html', context=context)


def content(request, username):
    """ 返回 用户登陆后的内容页面 """
    return render(request, 'login/main.html', {'username': username})


def logout(request):
    """ Logout . """

    auth.logout(request)

    return HttpResponseRedirect(reverse('login:login'))


@login_required
def reset(request):
    return HttpResponse('Welcome to  the reset password page of dwms .')
